import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;


public class PSPNotify extends Thread{
	private static HashMap<String, ArrayList<PSPEvent>> channel_map;
	private static HashMap<String, String> subscribe_map;
	private static int port = 80;
	private static InetAddress IP_address = null;
	
	// Initialize the Thread with the tow relevant hash maps
	PSPNotify(HashMap<String, ArrayList<PSPEvent>> channels, HashMap<String, String> subscribers){
		channel_map = channels;
		subscribe_map = subscribers;
	}
	
	// Update the client connection info
	public void setConnectionInfo(InetAddress c_IP_address, int c_port){
		port = c_port;
		IP_address = c_IP_address;
	}
	
	// Go through the channel_map and subscriber_map and send out updates to important parties.
	public void run(){
		// Crawl through the subscribe_map to see which clients are subscribed to specific channels
		Set<String> user_set = subscribe_map.keySet();
		Iterator<String> itr = user_set.iterator();
		// Now iterate through the keys and for each, check to see if any events exist.  If so, then 
		// Notify the subscribers
		while (itr.hasNext()){
			String channel_name = itr.next();
			
			ArrayList<PSPEvent> current_events = channel_map.get(channel_name);
			
			// If there are un-sent events on that channel, send them to the subscribers
			if (current_events.size() > 0){
				String[] channel_subscribers = subscribe_map.get(channel_name).split("\0");
				// Send a notification to each subscribers
				for (int i=0; i<channel_subscribers.length; i++){
					for (int j=0; j<current_events.size(); j++){
						PSPEvent the_event = current_events.get(j);
						byte [] sendData = PSPPacket.create_packet(PSPAction.SERVER_NOTIFY, channel_subscribers[i], 0, channel_name, PSPPubSchedule.IMMEDIATELY_UPON_PUBLISHING, the_event.getEventInformation());
						DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IP_address, port);
						
					}
				}
			}
		}
	}

}
